const { DataTypes } = require('sequelize')
const { sequelize } = require('../config/database')

const ChatSession = sequelize.define('ChatSession', {
  id: {
    type: DataTypes.STRING(50),
    primaryKey: true,
    allowNull: false
  },
  userId: {
    type: DataTypes.STRING(50),
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  title: {
    type: DataTypes.STRING(255),
    allowNull: false,
    defaultValue: '新对话'
  },
  systemPrompt: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  aiConfigId: {
    type: DataTypes.UUID,
    allowNull: true,
    references: {
      model: 'ai_configs',
      key: 'id'
    }
  },
  messageCount: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0
  },
  lastMessageAt: {
    type: DataTypes.DATE,
    allowNull: true
  },
  isPinned: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: true
  },
  tags: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: []
  },
  metadata: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: {
      totalTokens: 0,
      totalCost: 0,
      createdFrom: 'web'
    }
  }
}, {
  tableName: 'chat_sessions',
  timestamps: true,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  indexes: [
    {
      fields: ['userId']
    },
    {
      fields: ['aiConfigId']
    },
    {
      fields: ['isActive']
    },
    {
      fields: ['isPinned']
    },
    {
      fields: ['lastMessageAt']
    },
    {
      fields: ['createdAt']
    }
  ]
})

module.exports = ChatSession